package com.zyy.smartcity1129.movecar;

import android.app.AlertDialog;
import android.content.Intent;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.zyy.smartcity1129.BaseFragment;
import com.zyy.smartcity1129.R;
import com.zyy.smartcity1129.data.MoveCarInfo;
import com.zyy.smartcity1129.data.SelfMoveCarInfo;
import com.zyy.smartcity1129.data.UserInfo;
import com.zyy.smartcity1129.data.city;
import com.zyy.smartcity1129.util.Http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import okhttp3.RequestBody;

/**
 * @ClassName: SelfMoveFragment$
 * @Description: 作用
 * @Author: letquit
 * @CreateDate: 4/12/2021$
 * @Version: 1.0
 */
public class SelfMoveFragment extends BaseFragment {
    private EditText editMoveCarNum;
    private TextView tvMoveMyName;
    private TextView tvMoveMyPhone;
    private TextView tvMoveMyId;
    private Spinner spinnerProvince;
    private Spinner spinnerCity;
    private Spinner spinnerDistrict;
    private EditText editMoveMyAddress;
    private ImageView imgMoveCar;
    private Button btnMoveSubmit;
    private TextView tvDialogCarNum, tvDialogCarPhone;
    private Button btnDialogCancel, btnDialogOK;
    List<city.DataBean> data;
    //    spinner
    List<String> sProvince,sCity,sDistrict;
    List<UserInfo.UserBean> lists;
    String province, city, district;
    int provinceId;
    String mAddress = "";

    @Override
    protected int layId() {
        return R.layout.f_selfmove;
    }

    @Override
    protected String title() {
        return null;
    }

    @Override
    protected boolean back() {
        return false;
    }

    @Override
    protected Boolean bottom() {
        return null;
    }

    @Override
    protected void init(View iv) {
        MoveCarFragment.mutableMoveCar.postValue("自助移车");
        initView(iv);
        initThread();
        initData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Glide.with(imgMoveCar.getContext()).load(data.getExtras().get("data")).into(imgMoveCar);
    }

    private void initData() {
        try {
            InputStreamReader inputStreamReader=new InputStreamReader(getActivity().getAssets().open("省市区三级联动.txt"));
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
            String m;
            StringBuilder stringBuilder=new StringBuilder();
            while ((m= bufferedReader.readLine())!=null){
                stringBuilder.append(m);
            }
            data= new Gson().fromJson(stringBuilder.toString(),city.class).getData();
        } catch (IOException e) {
            e.printStackTrace();
        }

        imgMoveCar.setOnClickListener(v -> {
            startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), 1);
        });

        sProvince=new ArrayList<>();
        sCity=new ArrayList<>();
        sDistrict=new ArrayList<>();
        for (city.DataBean c:data){
            sProvince.add(c.getProvinceName());
        }

        ArrayAdapter<String> ads1=new ArrayAdapter(getContext(), R.layout.sp_item,sProvince);
        ArrayAdapter<String> ads2=new ArrayAdapter(getContext(), R.layout.sp_item,sCity);
        ArrayAdapter<String> ads3=new ArrayAdapter(getContext(), R.layout.sp_item,sDistrict);
        spinnerProvince.setAdapter(ads1);
        spinnerCity.setAdapter(ads2);
        spinnerDistrict.setAdapter(ads3);

        spinnerProvince.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String str = (String) parent.getItemAtPosition(position);
                Log.i("TAG", str);
                sCity.clear();
                province = sProvince.get(position);
                provinceId = position;
                for (city.DataBean.MallCityListBean mBean : data.get(position).getMallCityList()) {
                    sCity.add(mBean.getCityName());
                }
                ads2.notifyDataSetChanged();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinnerCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String str = (String) parent.getItemAtPosition(position);
                Log.i("TAG", str);
                sDistrict.clear();
                city = sCity.get(position);
                for (city.DataBean.MallCityListBean.MallAreaListBean mBean : data.get(provinceId).getMallCityList().get(position).getMallAreaList()) {
                    sDistrict.add(mBean.getAreaName());
                }
                ads3.notifyDataSetChanged();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinnerDistrict.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String str = (String) parent.getItemAtPosition(position);
                Log.i("TAG", str);
                district = sDistrict.get(position);
//                Toast.makeText(getContext(), "当前：" + province + " " + city + " " + district, Toast.LENGTH_SHORT).show();
                mAddress = province + city + district;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        btnMoveSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = "";
                String otherCarNum = editMoveCarNum.getText().toString();
                String otherCarPhone = "12345678901";
                String address;
                String moreAddress = editMoveMyAddress.getText().toString();
                if (otherCarNum.equals("")) {
                    str += "车牌号";
                    if (moreAddress.equals("")) {
                        str += "和具体地址";
                    }
                    Toast.makeText(getContext(), "请输入" + str, Toast.LENGTH_SHORT).show();
                } else {
                    if (moreAddress.equals("")) {
                        str += "具体地址";
                        Toast.makeText(getContext(), "请输入" + str, Toast.LENGTH_SHORT).show();
                    } else {
                        address = mAddress + moreAddress;
                        AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
                        View view = LayoutInflater.from(getActivity().getBaseContext()).inflate(R.layout.dialog_movecar, null, false);
                        dialog.setView(view);
                        tvDialogCarNum = view.findViewById(R.id.tvDialogCarNum);
                        tvDialogCarPhone = view.findViewById(R.id.tvDialogCarPhone);
                        btnDialogOK = view.findViewById(R.id.btnDialogOK);
                        btnDialogCancel = view.findViewById(R.id.btnDialogCancel);
                        tvDialogCarNum.setText("车牌号：" + otherCarNum);
                        tvDialogCarPhone.setText("车主电话：" + otherCarPhone);
                        AlertDialog mdialog = dialog.show();
                        btnDialogOK.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Log.i("TAG", address + "address");
                                String area = spinnerDistrict.getSelectedItem().toString();
                                String city = spinnerCity.getSelectedItem().toString();
                                String province = spinnerProvince.getSelectedItem().toString();
                                String idCard = tvMoveMyId.getText().toString();
                                String tel = tvMoveMyPhone.getText().toString();
                                JsonObject jsonObject = new JsonObject();
                                jsonObject.addProperty("address", moreAddress);
                                jsonObject.addProperty("area", area);
                                jsonObject.addProperty("city", city);
                                jsonObject.addProperty("province", province);
                                jsonObject.addProperty("idCard", idCard);
                                jsonObject.addProperty("plateNo", otherCarNum);
                                jsonObject.addProperty("tel", tel);
//                                jsonObject.addProperty("photo", );
                                th(() -> {
                                    String res = Http.getInstance().get("/prod-api/api/park/car/move", RequestBody.create(Http.m, jsonObject.toString()), SelfMoveCarInfo.class, 1).getMsg();
                                    ui(() -> {
                                        long result = new MoveCarDataAdapter().insert(getContext(), new MoveCarInfo(otherCarNum, otherCarPhone, address));
                                        Log.i("TAG", result + "result" + " res" + res);
                                        if (result > 0) {
                                            Toast.makeText(getContext(), "已提交", Toast.LENGTH_SHORT).show();
                                        } else {
                                            Toast.makeText(getContext(), "提交失败", Toast.LENGTH_SHORT).show();
                                        }
                                        mdialog.dismiss();
                                    });
                                });

                            }
                        });
                        btnDialogCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mdialog.dismiss();
                            }
                        });
                    }
                }
            }
        });
    }

    private void initThread() {
        th(() -> {
            lists = new ArrayList<>();
            UserInfo.UserBean userBeans = Http.getInstance().get("/prod-api/api/common/user/getInfo", null, UserInfo.class, 1).getUser();
            String name = userBeans.getUserName();
            String phoneNum = userBeans.getPhonenumber();
            String idCard = String.valueOf(userBeans.getIdCard());
            ui(() -> {
                tvMoveMyName.setText(name);
                tvMoveMyPhone.setText(phoneNum);
                tvMoveMyId.setText(idCard);
            });
        });
    }

    private void initView(View iv) {
        editMoveCarNum = (EditText) iv.findViewById(R.id.editMoveCarNum);
        tvMoveMyName = (TextView) iv.findViewById(R.id.tvMoveMyName);
        tvMoveMyPhone = (TextView) iv.findViewById(R.id.tvMoveMyPhone);
        tvMoveMyId = (TextView) iv.findViewById(R.id.tvMoveMyId);
        spinnerProvince = (Spinner) iv.findViewById(R.id.spinnerProvince);
        spinnerCity = (Spinner) iv.findViewById(R.id.spinnerCityz);
        spinnerDistrict = (Spinner) iv.findViewById(R.id.spinnerDistrict);
        editMoveMyAddress = (EditText) iv.findViewById(R.id.editMoveMyAddress);
        imgMoveCar = (ImageView) iv.findViewById(R.id.imgMoveCar);
        btnMoveSubmit = (Button) iv.findViewById(R.id.btnMoveSubmit);
    }
}
